package com.github.niefy.modules.wx.testController;

import com.github.niefy.modules.wx.form.WxQrCodeForm;
import com.github.niefy.modules.wx.service.WxQrCodeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;



@Slf4j
@Controller
@RequestMapping("/test/scan")
@Tag(name = "测试功能用接口")
public class ScanBindTestController {

    @Autowired
    private WxQrCodeService wxQrCodeService;
    @Autowired
    private WxMpService wxMpService;

    @ResponseBody
    @GetMapping("/bind")
    //@RequiresPermissions("sys:log:list")
    @Operation(summary = "生成模拟其他平台用户名和场景二维码",description = "")
    public ScanBindModule bind(@CookieValue String appid, @RequestParam Map<String, Object> params) throws WxErrorException {
        //String imgUrl = "";
        String username = "";
        //生成一个sceneId,以用户Id + :bind为标识
        username = RandomStringUtils.randomAlphanumeric(5) + ":bind";
        //log.info(username + "与openId:" + openId +"用户绑定")
        wxMpService.switchoverTo(appid);
        WxQrCodeForm form = WxQrCodeForm.builder().sceneStr(username).expireSeconds(2592000).isTemp(true).build();
        //获取ticket
        WxMpQrCodeTicket ticket = wxQrCodeService.createQrCode(appid,form);
        // 获得在系统临时目录下的文件，需要自己保存使用，注意：临时文件夹下存放的文件不可靠，不要直接使用
        //File file = wxMpService.getQrcodeService().qrCodePicture(ticket);

        return new ScanBindModule("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket.getTicket(), username.substring(0, username.indexOf(':')));
    }

}
